package com.example.tnot.Teacher;


import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresPermission;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.tnot.R;
import com.example.tnot.api.CameraUtil;
import com.example.tnot.api.SocketClient;

import java.io.ByteArrayOutputStream;

public class
TeacherLiveActivity extends AppCompatActivity implements SocketClient.LiveStreamListener {
    private static final int CAMERA_PERMISSION_REQUEST_CODE = 1001;
    private static final long SEND_INTERVAL = 200;
    private PreviewView previewView;
    private String currentRoomId;
    private TextView roomIdTv;
    private long lastSendTime = 0;
    private TextView viewerCountTv;
    private SocketClient socketClient;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_teacher_live);

        previewView = findViewById(R.id.preview_view);
        roomIdTv = findViewById(R.id.room_id_tv);
        viewerCountTv = findViewById(R.id.viewer_count_tv);
        socketClient = SocketClient.getInstance();
        socketClient.connect();
        while(!socketClient.getmSocket())
        {;}
//        currentRoomId = "1";
//        roomIdTv.setText("直播ID: " + "1");
        roomIdTv.setText("直播ID: 连接中...");
        socketClient.teacherConnect();
        socketClient.setLiveListener(this);
        checkCameraPermission();
        socketClient.createLiveRoom();
        // 检查摄像头权限
        checkCameraPermission();

    }

    private void checkCameraPermission() {
        Log.d("TeacherLiveActivity", "检查摄像头权限");
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED) {
            Log.d("TeacherLiveActivity", "权限已授予，准备初始化摄像头");
            initCamera();
            Log.d("摄像头","权限已授予，初始化摄像头");
        } else {
            Log.d("TeacherLiveActivity", "权限未授予，请求权限");
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    CAMERA_PERMISSION_REQUEST_CODE);
        }
    }

    @RequiresPermission(Manifest.permission.CAMERA)
    private void initCamera() {
        Log.d("TeacherLiveActivity", "开始初始化摄像头");
        CameraUtil.startCamera(this, previewView, (frameData, width, height) -> { // 接收宽高参数
            Log.d("TeacherLiveActivity", "收到原始视频帧数据，分辨率: " + width + "x" + height + "，长度: " + frameData.length);

            // 使用摄像头实际宽高转换JPEG
            byte[] jpegFrameData = convertToJpeg(frameData, width, height);
            if (jpegFrameData == null) {
                Log.e("TeacherLiveActivity", "帧格式转换失败，跳过该帧");
                return;
            }

            // 发送逻辑保持不变...
            if (currentRoomId != null) {
                long currentTime = System.currentTimeMillis();
                if (currentTime - lastSendTime >= SEND_INTERVAL) {
                    socketClient.sendLiveFrame(currentRoomId, jpegFrameData);
                    lastSendTime = currentTime; // 更新时间戳
                    Log.d("发送帧", "JPEG长度: " + jpegFrameData.length);
                }
            }
        });
    }

    // 新增：将原始帧数据（假设为YUV格式，摄像头常见输出）转换为JPEG
    private byte[] convertToJpeg(byte[] yuvData, int frameWidth, int frameHeight) {
        // 1. 基础校验：宽高和数据不能为空
        if (yuvData == null || yuvData.length == 0) {
            Log.e("ConvertJPEG", "YUV数据为空");
            return null;
        }
        if (frameWidth <= 0 || frameHeight <= 0) {
            Log.e("ConvertJPEG", "无效的宽高参数: " + frameWidth + "x" + frameHeight);
            return null;
        }

        // 2. 验证NV21格式的数据长度是否匹配（宽*高*3/2）
        int expectedLength = frameWidth * frameHeight * 3 / 2;
        if (yuvData.length != expectedLength) {
            Log.e("ConvertJPEG", "YUV数据长度不匹配！预期: " + expectedLength + ", 实际: " + yuvData.length);
            return null;
        }

        try {
            // 3. 使用帧的实际宽高创建YuvImage（而非previewView的宽高）
            YuvImage yuvImage = new YuvImage(
                    yuvData,
                    ImageFormat.NV21,  // 明确指定格式（需与摄像头输出一致）
                    frameWidth,
                    frameHeight,
                    null  // 连续存储的NV21无需strides参数
            );

            // 4. 压缩为JPEG
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            boolean compressSuccess = yuvImage.compressToJpeg(
                    new Rect(0, 0, frameWidth, frameHeight),
                    80,  // 压缩质量（0-100）
                    outputStream
            );

            if (!compressSuccess) {
                Log.e("ConvertJPEG", "YUV转JPEG压缩失败");
                return null;
            }

            return outputStream.toByteArray();
        } catch (Exception e) {
            Log.e("ConvertJPEG", "转换过程异常: " + e.getMessage(), e);
            return null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.d("TeacherLiveActivity", "权限请求结果回调，requestCode: " + requestCode);
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("TeacherLiveActivity", "权限请求结果: " + (grantResults[0] == PackageManager.PERMISSION_GRANTED ? "授予" : "拒绝"));
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    Log.e("TeacherLiveActivity", "权限检查失败，无法初始化摄像头");
                    return;
                }
                initCamera();
                Log.d("摄像头","权限申请成功，初始化摄像头");
            } else {
                Log.w("TeacherLiveActivity", "权限请求结果为空");
                Toast.makeText(this, "需要摄像头权限才能进行直播", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }

    // 其他重写方法保持不变...
    @Override
    public void onLiveRoomCreated(String roomId) {
        runOnUiThread(() -> {
            currentRoomId = roomId;
            roomIdTv.setText("直播ID: " + roomId);
            Log.d("数据","直播间ID更新为: " + roomId);
        });
    }

    @Override
    public void onLiveStreamData(byte[] frameData) {
        Log.d("数据","收到预览帧数据，长度: " + frameData.length);
    }

    @Override
    public void onLiveError(String message) {
        runOnUiThread(() -> Toast.makeText(this, "直播错误: " + message, Toast.LENGTH_SHORT).show());
    }

    @Override
    public void onViewerCountChanged(int count) {
        runOnUiThread(() -> viewerCountTv.setText("观众: " + count + "人"));
    }

    @Override
    public void onLiveRoomClosed() {
        runOnUiThread(() -> {
            Toast.makeText(this, "直播已结束", Toast.LENGTH_SHORT).show();
            finish();
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (currentRoomId != null) {
            socketClient.leaveLiveRoom(currentRoomId);
        }
        CameraUtil.stopCamera(); // 新增：停止摄像头
    }
}